/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

import { TaskDetails } from '@ohos/hvigor';

import { PreBuild } from '../pre-build.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { DEFAULT_MAIN_FILED_FILE_SUFFIX, OhosHarTask, OhPackageJsonOpt, PackageJsonOpt } from '../task/ohos-har-task.js';

export let packageJsonValidMainField: string | undefined;

/**
 * 闭源Har打包发布前需要对package.json文件进行处理和增加一些信息
 * 当前该任务执行处理很快,先不需要做增量
 */
export abstract class CoreProcessPackageJson extends OhosHarTask {
  protected readonly generatePmDir;

  protected constructor(taskService: TargetTaskService, taskDetails: TaskDetails) {
    super(taskService, taskDetails);
    this.generatePmDir = this.pathInfo.getGeneratePmDir();
  }

  protected doTaskAction(): void {
    if (this._harExtendInfo.isObfuscatedHar() || this.targetService.isByteCodeHar()) {
      this.getGeneratePackageJsonObj();
    }
  }

  private getGeneratePackageJsonObj(): PackageJsonOpt | OhPackageJsonOpt {
    const validMainField = this.getPackageJsonValidMainField();

    // 通过export一个变量,传递已经获取过的har中package.json的有效的main字段,不用重复调用方法获取
    packageJsonValidMainField = validMainField;

    const typesFieldValue = this.getDefaultTypesValueByMainField(validMainField);

    const packageJsonObj: PackageJsonOpt = this.packageJsonObj as PackageJsonOpt;

    // 如果main字段存在且以.js结尾的情况下不对types进行处理，其他场景均赋值
    if (!(packageJsonObj.main && packageJsonObj.main.endsWith('.js'))) {
      packageJsonObj.types = typesFieldValue;
    }
    packageJsonObj.main = this.replaceMainFieldSuffix(validMainField);

    this.addArtifactType(packageJsonObj);

    return packageJsonObj;
  }

  protected abstract addArtifactType(packageJsonObj: PackageJsonOpt | OhPackageJsonOpt): void;

  private getDefaultTypesValueByMainField(mainFiled: string): string {
    let result;
    DEFAULT_MAIN_FILED_FILE_SUFFIX.forEach((suffix) => {
      if (mainFiled.endsWith(suffix)) {
        result = mainFiled.replace(suffix, `.d${suffix}`);
      }
    });

    return result ?? 'index.d.ets';
  }

  initTaskDepends(): void {
    this.declareDepends(PreBuild.name);
  }

  private replaceMainFieldSuffix(mainField: string): string {
    const hasField = this.hasUseTsHarField();
    for (const suffix of DEFAULT_MAIN_FILED_FILE_SUFFIX) {
      if (hasField) {
        return mainField.replace(suffix, '.ts');
      }

      if (mainField.endsWith(suffix)) {
        return mainField.replace(suffix, '.js');
      }
    }
    return mainField.concat('.js');
  }
}
